"""Read Image
.. helpdoc::
Read in images as arrays.  These can be furhter manipulated in the image analysis tools, and also manipulated with other array manipulation tools."""

"""
<widgetXML>    
    <name>Read Image</name>
    <icon>default.png</icon>
    <tags> 
        <tag>Matplotlib Plotting</tag> 
    </tags>
    <summary>Read an image into the schema.</summary>
    <author>
        <authorname>Kyle R. Covington</authorname>
        <authorcontact>kyle@red-r.org</authorcontact>
    </author>
</widgetXML>
"""
from OWRpy import * 
import redRGUI, signals 
import numpy, scipy, pylab
import glob, os

import redRi18n, globalData
_ = redRi18n.get_(package = 'base')
class readImage(OWRpy):
    def __init__(self, **kwargs):
        OWRpy.__init__(self, **kwargs)
        
        """.. rrsignals::"""
        self.outputs.addOutput('id0', _('Image'), signals.base.NumpyArray)
        box = redRGUI.base.widgetBox(self.controlArea, orientation = 'horizontal')
        self.filecombo = redRGUI.base.fileNamesComboBox(box, label=_('Files'), displayLabel=False,
        orientation='horizontal', callback=self.scanNewFile)
        #self.filecombo.setSizePolicy(QSizePolicy.MinimumExpanding,QSizePolicy.Preferred)
        
        """.. rrgui::
            :description: `Opens a file browser to search for files.`
        """
        redRGUI.base.button(box, label = _('Browse'), callback = self.browseFile)
        box2 = redRGUI.base.widgetBox(self.controlArea, orientation = 'horizontal')
        self.GUI_glob = redRGUI.base.lineEdit(box2, label = "File Filter:", toolTip = "Specify the file filter to use in the selected directory for itteration. ex: picture*.PNG")
        redRGUI.base.button(box2, label = "Itterate", callback = self.itterateFiles)
        redRGUI.base.button(self.controlArea, label = "Clear", callback = self.clearImage)
        self.GUI_showImage = redRGUI.base.TFCheckBox(box2, label = "Show Image", setChecked = False)
        
        self.GUI_plot = redRGUI.RedRMatplotlib.mplPlot(self.controlArea)
    def clearImage(self):
        self.GUI_plot.subPlot.clear()
        self.GUI_plot.canvas.draw()
    def browseFile(self): 
        import redREnviron
        fn = QFileDialog.getOpenFileName(self, _("Open File"), redREnviron.settings['workingDir'],
        "Text file (*.png *.jpg *.jpeg *.bmp);; All Files (*.*)")
        if fn.isEmpty(): return
        fn = unicode(fn)
        redREnviron.settings['workingDir'] = os.path.split(fn)[0]
        self.filecombo.addFile(fn)
        self.saveGlobalSettings()
        self.scanNewFile()
    def scanNewFile(self):
        """This function scans the file specified by the filecombo.  If the filecombo is empty, then no action is taken.  The resulting image will be loaded into the image."""
        fn = self.filecombo.getCurrentFile()
        self.processFile(fn)
        
    def processFile(self, fn):
        if not fn:
            self.status.setText(_('No file selected'))
            return 
        # myarray is the image array that we can do some work with, like plotting.
        try:
            myarray = pylab.imread(unicode(fn))
        except Exception as inst:
            self.status.setText(_('Exception occured while reading file %s') % inst)
            
            return
        
        if self.GUI_showImage.checked() == "TRUE":
            self.GUI_plot.subPlot.imshow(myarray)
            self.GUI_plot.canvas.draw()
        
        newdata = signals.base.NumpyArray(self, data = myarray)
        newdata.setOptionalData(name = 'filename', data = fn, creatorWidget=self, description = "File Name of the read file", extra=None)
        globalData.setGlobalData(self, "ImageFileName", data = fn, description = "File Name of the read file")
        self.rSend('id0', newdata)
        
    def itterateFiles(self):
        fns = QFileDialog.getOpenFileNames(self, _("Select Files"), redREnviron.settings['workingDir'],
        "Text file (*.png *.jpg *.jpeg *.bmp);; All Files (*.*)")
        if len(fns) == 0: return
        redREnviron.settings['workingDir'] = os.path.split(unicode(fns[0]))[0]
        for fn in fns:
            self.processFile(unicode(fn))
        
        
